package com.yimi.appstore.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;

import com.yimi.appstore.activity.ApkExplorerActivity.InstalledExpandableAdapter;
import com.yimi.appstore.adapter.MyAdapter;

/**
 * Bitmap帮助类
 * 
 * @author Tank
 * 
 */
public class BitmapUtil {
	private static String TAG = "BitmapUtil";
	private static AsyncTask asyncTask;
	private static String PREFIX = "http://www.warenla.com/picture/appstore/";

	/**
	 * 销毁掉异步加载图片任务
	 */
	public static void destroyedAsyncTask() {
		if (asyncTask != null && !asyncTask.isCancelled()) {
			asyncTask.cancel(true);
		}
	}

	/**
	 * 获取网络图片，如果获取不到再重新获取，最多重复5次
	 * 
	 * @param params
	 * @return
	 */
	public static Bitmap getHttpBitmap2(String params) {
		Bitmap bitmap = null;
		for (int j = 0; j < 5; j++) {
			bitmap = BitmapUtil.getHttpBitmap(params);
			if (bitmap != null) {
				break;
			}
		}
		return bitmap;
	}

	/**
	 * 从服务器中获取图片
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getHttpBitmap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		if (url != null) {
			try {
				Log.d(TAG, url);
				if (!url.startsWith("http://"))
					myFileUrl = new URL(PREFIX + url);
				else
					myFileUrl = new URL(url);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			if (myFileUrl != null) {
				try {
					HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
					conn.setConnectTimeout(0);
					conn.setDoInput(true);
					conn.connect();
					InputStream is = conn.getInputStream();
					bitmap = BitmapFactory.decodeStream(is);
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return bitmap;
	}

	/**
	 * 异步获取网络图片
	 * 
	 * @param myAdapter
	 *            需要更新图片的适配器
	 * @param fromUrl
	 *            在适配器容器中，图片的地址对应的key
	 * @param toIcon
	 *            在适配器容器中，图片对应的key
	 */
	public static void updateAdapterBitmap(final ListView listView, final MyAdapter myAdapter, final String paramsKey,
			final String resultKey) {
		if (myAdapter != null) {
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
			asyncTask = new AsyncTask<Void, Void, Void>() {
				@Override
				protected Void doInBackground(Void... params) {
					List<HashMap<String, Object>> listData = myAdapter.getListData();
					for (;;) {
						if (listView.getLastVisiblePosition() > -1) {
							break;
						}
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					for (int i = listView.getFirstVisiblePosition(), size = listView.getLastVisiblePosition(); i <= size; i++) {
						if (listData.size() > i) {
							HashMap<String, Object> item = listData.get(i);
							if (!item.containsKey(resultKey) || item.get(resultKey) == null) {
								if (item.containsKey(paramsKey) && !item.get(paramsKey).toString().trim().equals("")) {
									item.put(resultKey, BitmapUtil.getHttpBitmap2(item.get(paramsKey).toString()));
									publishProgress();
								}
							}
						}
					}
					return null;
				}

				@Override
				protected void onProgressUpdate(Void... values) {
					super.onProgressUpdate(values);
					myAdapter.notifyDataSetChanged();
				}
			}.execute();
		}
	}
	
	
	/**
	 * 异步获取app图片
	 * 
	 * @param myAdapter
	 *            需要更新图片的适配器
	 * @param paramsKey
	 *            在适配器容器中，图片的地址对应的key
	 * @param resultKey
	 *            在适配器容器中，图片对应的key
	 */
	public static void updateAdapterLocalBitmap(final ListView listView, final InstalledExpandableAdapter myAdapter, final String paramsKey,
			final String resultKey , final Context context ) {
		if (myAdapter != null) {
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
			asyncTask = new AsyncTask<Void, Void, Void>() {
				@Override
				protected Void doInBackground(Void... params) {
					List<HashMap<String, Object>> listData = myAdapter.getListData();
					for (;;) {
						if (listView.getLastVisiblePosition() > -1) {
							break;
						}
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					for (int i = listView.getFirstVisiblePosition(), size = listView.getLastVisiblePosition(); i <= size; i++) {
						if (listData.size() > i) {
							HashMap<String, Object> item = listData.get(i);
							if (!item.containsKey(resultKey) || item.get(resultKey) == null) {
								if (item.containsKey(paramsKey) && !item.get(paramsKey).toString().trim().equals("")) {
									item.put(resultKey, Util.getBitmapBypn((String)item.get(paramsKey), context));
									publishProgress();
								}
							}
						}
					}
					return null;
				}

				@Override
				protected void onProgressUpdate(Void... values) {
					super.onProgressUpdate(values);
					myAdapter.notifyDataSetChanged();
				}
			}.execute();
		}
	}
}
